import os
import cv2
import re
from paddleocr import PaddleOCR, draw_ocr
import numpy as np
from io import BytesIO
os.environ["APPBUILDER_TOKEN"] = ""
import re
import appbuilder
import requests
from PIL import Image
def shi_bie(url):
    # url_pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
    # urls = []
    # print(url)
    # for i in url:
    #     match = url_pattern.match(i)
    #     if match:
    #         urls.append(match.group())
    # # 使用requests从URL获取图片
    # print(urls)\
    det_model_dir = 'ch_PP-OCRv4_det'  # 检测模型目录
    rec_model_dir = 'ch_PP-OCRv4_rec_infer'  # 识别模型目录

    # 初始化OCR模型，使用指定的检测和识别模型
    ocr = PaddleOCR(
        use_gpu=False,  # 是否使用GPU进行推理，如果没有GPU请设置为False
        det_model_dir=det_model_dir,
        rec_model_dir=rec_model_dir,
        use_angle_cls=True,  # 如果您的模型支持方向分类，请设置为True
        lang='ch'  # 语言类型，对于中文OCR，设置为'ch'
    )
    texts = []
    for i in url:
        print(i)
        url_match = re.search(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', i)
        i = url_match.group()
        print(i)
        response = requests.get(i)
        if response.status_code == 200:
            # 从响应内容中获取图片数据
            image_data = response.content
            # 使用PIL打开图片
            image = Image.open(BytesIO(image_data))
            byte_arr = BytesIO()
            image.save(byte_arr, format='PNG')  # Convert to PNG format if necessary
            image_in_bytes = byte_arr.getvalue()

            # 构建输入信息
            inp = appbuilder.Message(content={"raw_image": image_in_bytes})

            # 运行手写体识别
            handwrite_ocr = appbuilder.HandwriteOCR()
            out = handwrite_ocr.run(inp)
            # 打印识别结果
            data = out.content
            texts += [content['text'] for content in data['contents'] if content['position']['height'] >= 30]
            return texts
        else:
            return "图片读取失败"
if __name__ == '__main__':
    print(shi_bie(["http://43.139.56.166:9001/ksxt/02f9be1780f057cede43e46c6002e08.jpg"]))
